package net.gxf.findinfo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import net.gxf.common.etf.Stock;
import net.gxf.common.etf.StockETF;
import net.gxf.common.util.QueryStockUtil;


/**
 * 根据data.txt中的股票代码查询最新股票价格，然后输出到文件中
 * 
 * @author Administrator
 * 
 */
public class FindInfo {
	private Map<String, StockETF> dataMap = new HashMap<String, StockETF>();

	public static void main(String[] args) {
		FindInfo findInfo = new FindInfo();
		findInfo.deal("data.txt");
		findInfo.export("C:/data.txt");
	}

	public void deal(String path) {
		// 加载数据，解析数据
	/*	InputStreamReader inputStreamReader = new InputStreamReader(this
				.getClass().getClassLoader().getResourceAsStream(path));*/
		try {
			InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(path));
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String readLine;
			readLine = bufferedReader.readLine();
			while (true) {
				String[] keyvalue = readLine.split("\t");
				Stock info = QueryStockUtil.queryByCode(keyvalue[0].trim(), "sz");
				//info.setCount(Integer.valueOf(keyvalue[2].trim()));
				StockETF stockETF=new StockETF();
				stockETF.copyFromStock(info);
				dataMap.put(keyvalue[0], stockETF);
				// listMap.put(String.valueOf(i),keyvalue[0]);
				readLine = bufferedReader.readLine();
				if (readLine == null)
					break;
			}
			System.out.println(dataMap.size());
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void export(String path) {
		// 查询并生成数据
		StringBuffer buffer = new StringBuffer();
		Iterator<String> iterator = dataMap.keySet().iterator();
		while (iterator.hasNext()) {
			String next = iterator.next();
			StockETF info = dataMap.get(next);
			buffer.append(info.getCode()).append("\t");
			buffer.append(info.getName()).append("\t");
			buffer.append(info.getNumber()).append("\t");
			buffer.append(info.getCurrentPrice()).append("\t");
			buffer.append(info.getWorth()).append("\r\n");
		}
		File file = new File(path);
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			fileOutputStream.write(buffer.toString().getBytes());
			fileOutputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	public void clear(){
		dataMap.clear();
	}
}
